<template>
  <el-card :body-style="{ padding: '3px' }" style="border: 1px solid cornflowerblue">
    <div>
      <strong>归档文件夹：</strong>
      <el-autocomplete v-model="finalDirName" class="select_option" :fetch-suggestions="querySearchAsync" @select="((item)=>{handleFinalSelect(item)})"  :trigger-on-focus="false">
      </el-autocomplete>
      <el-button icon="el-icon-plus" size="mini" type="primary" v-if="isCreated" @click="addFinalDirHandle"></el-button>
      <span style="color: red" v-if="isCreated">该归档文件夹不存在，是否创建！</span>
    </div>
    <!--路径和搜索-->
    <el-form :inline="true" >
      <el-form-item label="路径：">
        <el-link  @click="curpath = [],changePath('')" disabled><strong>主目录</strong></el-link>
        <span>/</span>
        <el-link  :key="index" v-for="(item,index) in curpath" @click="changePath(getFilepath(index))">
          <strong>{{ item }}</strong> <span>/</span>
        </el-link>
      </el-form-item>
    </el-form>
    <!--列表-->
    <uploader :options="options" ref="finalUploader" :file-status-text="statusText" class="uploader-example"
              @file-success="onFileSuccess" @file-added="onFileAdd" @file-removed="onFileRemove" :key="aTabKey">
      <!--      //浏览器不支持将显示此内容-->
      <uploader-unsupport></uploader-unsupport>
      <uploader-drop>
        <div style="text-align: center;color: red">*文件拖拽至此可上传文件*</div>
        <el-table :data="finalList" border :default-sort ="{prop:'fileType',order:'ascending'}" v-loading="loading" stripe >
          <template slot="empty"><span>文件夹为空</span></template>
          <el-table-column prop="fileName" header-align="center" align="left" label="文件名称" :show-overflow-tooltip="true" sortable>
            <template slot-scope="scope">
              <div class="file_item_name" @dblclick="scope.row.isFouce? '':lookoverFileHandle(scope.row)">
                <i><icon-svg :name="getFileType(scope.row)" ></icon-svg></i>
                <input v-if="scope.row.isFouce" v-model="scope.row.fileName" v-focus @blur="blurFinalHandle(scope.row)"></input>
                <strong v-else>{{scope.row.fileName}}</strong>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="fileType" header-align="center" align="center" label="文件类型" sortable width="120" >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isDir" type="primary">文件夹</el-tag>
              <el-tag v-else type="info" plain>{{scope.row.fileType.replace('.','')}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="fileSize" header-align="center" align="center" label="文件大小" sortable width="120" >
            <template slot-scope="scope">
              {{getFileSizeHandle(scope.row.fileSize)}}
            </template>
          </el-table-column>
          <el-table-column prop="filePath" header-align="center" align="center" label="文件路径" v-if="isSearch"></el-table-column>
          <el-table-column header-align="center" align="left" width="195" label="操作" >
            <template slot-scope="scope">
              <el-tooltip class="item"  content="重命名" placement="left">
                <el-button type="primary" size="mini" icon="el-icon-edit-outline" @click="editFinalHandle(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip class="item"  content="删除" placement="left">
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteFinalHandle(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip class="item"  content="下载" placement="left-start" v-if="!scope.row.isDir">
                <el-button type="success" size="mini" icon="el-icon-download" @click="downloadFileHandle(scope.row)" :loading="scope.row.loading">
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!--          <uploader-btn>选择文件</uploader-btn>-->
      </uploader-drop>
      <div class="popup-container">
        <div class="header">
          <div class="title_span">上传列表</div>
          <div class="title_btn" >
            <i class="el-icon-minus" @click="panelShow = false" v-if="panelShow"></i>
            <i class="el-icon-copy-document" @click="panelShow = true" v-if="!panelShow"></i>
          </div>
        </div>
        <uploader-list class="content" v-if="panelShow">
          <div class="file-panel" slot-scope="props" >
            <ul class="file-list">
              <li v-for="file in props.fileList" :key="file.id">
                <uploader-file :class="'file_' + file.id" ref="files" :file="file" :list="true"></uploader-file>
              </li>
              <div class="no-file" v-if="!props.fileList.length">
                <div style="text-align: center;color: grey">--暂无待上传文件--</div>
              </div>
            </ul>
          </div>
        </uploader-list>
      </div>
    </uploader>
    <el-table :data="processList" border :key="proKey" v-if="processList.length > 0">
      <el-table-column prop="fileName" header-align="center" align="left" label="文件名"></el-table-column>
      <el-table-column prop="rate" header-align="center" align="left" label="拷贝进度">
        <template slot-scope="scope">
          <el-progress :percentage="scope.row.rate" :text-inside="true" :stroke-width="22"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="socketStopCopy(scope.row)">取消</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script>
import Vue from 'vue'
import {stringIsNull} from '@/utils'
import {getFileType,getFileSize} from '@/utils/others/fileutils'

// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})
export default {
  props: {
    params: {
      type: Object,
      default: {}
    }
  },
  data () {
    return {
      isConnected: true,
      loading: true,
      showImg: false,
      ipServer: '',
      projectNo: '',
      panelShow: false,
      statusText: {
        success: '成功了',
        error: '出错了',
        uploading: '上传中',
        paused: '暂停中',
        waiting: '等待中'
      },
      aTabKey: '',
      proKey: '',
      websocket: null,
      processList: [],
      finalList: [],
      selectItem: null, // 选择的记录文件
      contractItem: {}, // 对应的合同项
      timer: '', // 定时器
      options: {},
      finalDirName: '',
      isCreated: false,
      curpath: []
    }
  },
  computed: {
    username: {
      get () { return this.$store.state.user.name }
    }
  },
  methods: {
    init () {
      this.processList = []
      this.ipServer = this.params.ipServer
      this.projectNo = this.params.projectNo
      this.options = this.params.options
      this.getFinaldirByProjectNo(this.params.contractName).then(entity => {
        this.finalDirName = entity.fileName
        this.getFinalList(entity.fileName)
        this.curpath = [entity.fileName]
        this.loading = false
      })
      this.getIpconfigFromApi('socketIp').then(socketIp => {
        this.socketInit(socketIp)
      })
      this.aTabKey = Math.random()

      clearInterval(this.timer)
      let that = this
      this.timer = setInterval(function () {
        if (that.$refs.finalUploader.fileList.length > 0) {
          let completed = true
          for (let fileItem of that.$refs.finalUploader.fileList) {
            if (!fileItem.completed) {
              completed = false
            }
          }
          if (completed) {
            that.$refs.finalUploader.uploader.cancel()
          }
        }
      }, 10 * 1000)
    },
    // 获取参数Ip
    getIpconfigFromApi (keyParm) {
      this.loading = true
      return new Promise((resolve, reject) => {
        this.$http({
          url: this.$http.adornUrl('/sys/config/getNameByKey'),
          method: 'get',
          params: this.$http.adornParams({
            key: keyParm
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            resolve(data.config.paramValue)
          } else {
            this.$message.error(data.msg)
            reject(data)
          }
        })
      })
    },
    // socket服务初始化
    socketInit (socketIp) {
      this.websocket = null
      let that = this
      // 随机生成模拟用户id
      // 判断当前浏览器是否支持WebSocket
      if ('WebSocket' in window) {
        this.websocket = new WebSocket('ws:' + socketIp + '/websocket/file/' + this.username)
      } else {
        this.$message.error('不支持socket服务！')
      }
      // 连接发生错误的回调方法
      this.websocket.onerror = function () {
        this.$message.error('socket链接异常！')
      }
      // 连接成功建立的回调方法
      this.websocket.onopen = function (event) {
        console.log('socket已链接！')
      }
      // 接收到消息的回调方法
      this.websocket.onmessage = function (event) {
        console.log(JSON.parse(event.data))
        let eventParm = JSON.parse(event.data)
        switch (eventParm.type) {
          case 'thread':
            let threadItem = {
              fileName: eventParm.target,
              rate: 0,
              cId: eventParm.cId,
              fId: eventParm.fId
            }
            that.processList.push(threadItem)
            break
          case 'process':
            that.processList.forEach((item, index) => {
              if (item.fileName === eventParm.target) {
                item.rate = eventParm.rate
              }
            })

            break
          default:
            break
        }
        setTimeout(() => {
          // 如果其中的进度 为100 或 -1 则移除
          let proTempList = []
          that.processList.forEach((item, index) => {
            if (item.rate === 100 || item.rate === -1) {
              setTimeout(() => that.getFinalList(that.getDirByPatharr()), 1000)
            } else {
              proTempList.push(item)
            }
          })
          that.processList = proTempList
        }, 1000)
      }
    },
    sendCopyMessage (itemList) {
      let ids = []
      let repeatItem = []
      itemList.forEach((item) => {
        if (!stringIsNull(this.finalList.find( final => item.fileName === final.fileName))) {
          repeatItem.push(item)
        } else {
          ids.push(item.id)
        }
      })
      // 重复文件覆盖要提示
      let itemInfo = []
      repeatItem.forEach((repeat) => {
        itemInfo.push(repeat.fileName)
      })
      if (itemInfo.length > 0) {
        this.$confirm('【' + itemInfo.join('，') + '】' + '文件已经存在归档文件中，是否覆盖项目文件', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          repeatItem.forEach((repeat) => {
            ids.push(repeat.id)
          })
          this.deleteFinalById(ids).then(success => {
            this.socketSendCopy(ids)
          })
        }).catch(() => {
          this.socketSendCopy(ids)
        })
      } else {
        this.socketSendCopy(ids)
      }
    },
    // 通过websocket发送拷贝信息
    socketSendCopy (ids) {
      let message = {
        type: 'copy',
        ids: ids,
        fileName: this.getDirByPatharr()
      }
      this.websocket.send(JSON.stringify(message))
    },
    // 通过websocket发送停止拷贝信息
    socketStopCopy (item) {
      let message = {
        type: 'kill',
        cthId: item.cId,
        fthId: item.fId
      }
      this.websocket.send(JSON.stringify(message))
    },
    // 获取文件大小
    getFileSizeHandle (size) {
      return getFileSize(size)
    },
    // 根据数组获取文件路径
    getDirByPatharr () {
      let cPath = ''
      this.curpath.forEach((item,index) => {
        cPath += item + '/'
      })
      return cPath
    },
    // 获取文件路径
    getFilepath (num) {
      this.curpath = this.curpath.slice(0,num + 1)
      return this.getDirByPatharr()
    },
    // 跳转路径
    changePath (path) {
      this.getFinalList(path)
    },
    // 获取档案目录表
    getFinalList (contractName) {
      return new Promise((resolve, reject) => {
        this.$http({
          url: 'http://' + this.ipServer + '/webapi/rfile/finalList',
          method: 'get',
          params: this.$http.adornParams({
            curpath: contractName
          })
        }).then(({data}) => {
          this.finalList = data.list
        })
      })
    },
    // 获取归档文件夹
    getFinaldirByProjectNo (contractName) {
      return new Promise((resolve, reject) => {
        this.$http({
          url: 'http://' + this.ipServer + '/final/file/info',
          method: 'get',
          params: this.$http.adornParams({
            username: this.username,
            projectNo: this.projectNo,
            fileName: contractName
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            resolve(data.finalFile)
          } else {
            this.$message.error(data.msg)
            reject(data.msg)
          }
        })
      })
    },
    querySearchAsync (queryString, cb) {
      var list = [{}]
      if (!stringIsNull(queryString.trim())) {
        // 从后台获取到对象数组
        this.$http({
          url: 'http://' + this.ipServer + '/final/file/list',
          method: 'get',
          params: this.$http.adornParams({
            key: queryString.trim()
          })
        }).then(({data}) => {
          list = data.list.map( (item,index) => {
            return {
              id: index,
              value: item
            }
          })
          // 如果列表不存在 则提示是否创建
          if (stringIsNull(data.list.find(item => item === queryString.trim()))) {
            this.isCreated = true
          } else {
            this.isCreated = false
          }
          cb(list)
        })
      }
    },
    // 文本框输入失去焦点 （编辑归档文件）
    blurFinalHandle (item) {
      item.isFouce = false
      if (stringIsNull(item.fileName.trim()) || (item.oldName === item.fileName.trim()) ) {
        this.init()
      } else {
        this.$http({
          url: 'http://' + this.ipServer + '/final/file/updateName',
          method: 'post',
          data: this.$http.adornData({
            filePath: this.getDirByPatharr(),
            newName: item.fileName.trim(),
            oldName: item.oldName
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.getFinalList(this.getDirByPatharr())
          } else {
            this.$message.error(data.msg)
          }
        })
      }
    },
    // 编辑档案 （修改名称）
    editFinalHandle (item) {
      let list = [...this.finalList]
      for (let fileItem of list) {
        if (fileItem.fileName === item.fileName) {
          fileItem.isFouce = true
          fileItem.oldName = item.fileName
        } else {
          fileItem.isFouce = false
        }
      }
      this.finalList = list
    },
    // 添加归档文件夹
    addFinalDirHandle () {
      this.$http({
        url: 'http://' + this.ipServer + '/final/file/update',
        method: 'post',
        data: this.$http.adornData({
          fileName: this.finalDirName,
          projectNo: this.projectNo,
          createUsername: this.username
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.isCreated = false
          this.curpath[0] = this.finalDirName
          this.getFinalList(this.getDirByPatharr())
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    // 选择最终归档文件夹
    handleFinalSelect (item) {
      this.isCreated = false
      this.finalDirName = item.value
      this.getFinalList(this.finalDirName)
    },
    // 通过上传文件ID 删除归档文件
    deleteFinalById (ids) {
      return new Promise((resolve, reject) => {
        this.$http({
          url: 'http://' + this.ipServer + '/final/file/deleteFinalById',
          method: 'post',
          data: this.$http.adornData({
            'filePath': this.getDirByPatharr(),
            'ids': ids
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            resolve(data)
          }
        })
      })
    },
    // 删除归档文件
    deleteFinalHandle (item) {
      this.$confirm('确定删除档案【' + item.fileName + '】操作', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: 'http://' + this.ipServer + '/webapi/rfile/deleteFinal',
          method: 'post',
          data: this.$http.adornData({
            'filePath': this.getDirByPatharr(),
            'fileName': item.fileName
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500
            })
            this.getFinalList(this.getDirByPatharr())
          }
        })
      })
    },
    // 归档记录
    putLogToFinal (fileName) {
      return new Promise((resolve, reject) => {
        if (this.curpath.length > 0) {

        }
        this.$http({
          url: 'http://' + this.ipServer + '/final/log/save',
          method: 'post',
          data: this.$http.adornData({
            'filePath': this.finalDirName,
            'fileName': fileName,
            'createUsername': this.username
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            resolve(data)
          }
        })
      })
    },
    // 查看文件
    lookoverFileHandle (item) {
      this.isSearch = false
      let baseUrl = window.SITE_CONFIG['uploadUrl'] + 'file/'
      // 文件类型为 图片、pdf、word、excel、ppt、txt 可在线打开
      switch (getFileType(item)) {
        case 'FOLDER':
          let pathList = []
          for (let path of item.filePath.split('/')) {
            if (!stringIsNull(path)) pathList.push(path)
          }
          pathList.push(item.fileName)
          this.curpath = pathList
          this.changePath(this.getDirByPatharr())
          break
        // case 'EXCEL':
        // case 'WORD':
        // case 'PPT':
        //   window.open('https://view.officeapps.live.com/op/view.aspx?src=' + baseUrl + item.filePath + '/' + item.fileName)
        //   break
        case 'TEXT':
        case 'PICTURE':
        case 'PDF':
          window.open(baseUrl + item.filePath + '/' + item.fileName)
          break
        default:
          this.$message.error('当前文件不支持在线浏览！')
          break
      }
    },
    // 上传文件成功
    onFileSuccess (rootFile, file, response, chunk) {
      this.getFinalList(this.getDirByPatharr())
      this.putLogToFinal(file.name)
    },
    onFileAdd (file) {
      // let rPath = file.file.relativePath.substring(0,file.file.relativePath.lastIndexOf(file.file.name))
      // file.relativePath = this.selectItem.id + ',' + this.username + ',' + rPath
      // file.createUsername = this.username
      let rPath = file.file.relativePath.substring(0,file.file.relativePath.lastIndexOf(file.file.name))
      file.relativePath = this.getDirByPatharr() + rPath
      this.panelShow = true
    },
    // 上传时移除文件
    onFileRemove (file) {
      // console.log(file)
      let that = this
      // 延时两秒 删除上传未完成的 暂时文件
      if (file.completed === false) {
        setTimeout(function () {
          let confItem = {
            fileName: file.name + '.conf',
            dir: false
          }
          that.deleteFileFromApi(confItem)
          let tempItem = {
            fileName: file.uniqueIdentifier + '_tmp',
            dir: false
          }
          that.deleteFileFromApi(tempItem)
        },2000)
      }
    },
  }
}
</script>

<style lang="scss" scoped>
@import "src/assets/scss/_variables.scss";
.select_option /deep/ {
  .el-input__inner {
    color: red;
  }
}
.popup-container {
  position: relative;
  box-shadow: -2px -4px 5px $navbar--background-color;
  border: 1px $navbar--background-color solid;
  //right: 20px;
  //bottom: 30px;
  padding: 1px;
  z-index: 2001;
  width: 100%;
  -moz-user-select:none;		/* 火狐 */
  -webkit-user-select:none;	/* 谷歌 */
  -ms-user-select:none;		/* IE */
  user-select:none;
  .header {
    padding: 6px;
    background: $--color-primary;
    color: whitesmoke;
    display: flex;
    justify-content: space-between;
    width: 100%;
    .title_span {
      font-size: 15pt;
      font-weight: 700;
    }
    .title_btn{
      padding-right: 5px;
      i {
        font-size: 19pt;
        font-weight: 700;
        cursor: pointer;
      }
      i:hover{
        color: red;
      }
    }
  }
  .content {
    background: beige;
    height: 200px;
    overflow-y: auto;
  }
}

.file_item_name{
  background: rgba($--color-primary,0.1);
  text-align:left;
  padding: 1px;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  -khtml-user-select: none;
  user-select: none;
  i {
    font-size: 17pt
  }
  strong {
    font-size: 11pt;
  }
}
.file_item_name:hover {
  color: $navbar--background-color;
  cursor: pointer;
  text-decoration: underline;
}
</style>
